package com.example.faceapp;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.megvii.facepp.api.FacePPApi;
import com.megvii.facepp.api.IFacePPCallBack;
import com.megvii.facepp.api.bean.DetectResponse;
import com.megvii.facepp.api.bean.Face;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static android.graphics.Color.RED;
import static android.graphics.Color.YELLOW;

public class DetectActivity extends AppCompatActivity {
    private static final String API_KEY = "";//旷视科技 图片识别api key
    private static final String API_SECRET = "";//旷视科技 图片识别 api secret
    private ImageView iv_pic;
    private static final int PHOTO_REQUEST_CODE = 100;
    private Button btn_camera, btn_detect, btn_galley, btn_save;
    private String picPath;
    private Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detect);
        initView();
        initEvents();


    }
    private void initEvents() {
        btn_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(DetectActivity.this, "btn_camera", Toast.LENGTH_SHORT).show();
            }
        });
        btn_detect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toast.makeText(DetectActivity.this,"detect",Toast.LENGTH_SHORT).show();
                //把需要识别出的属性放入hashmap中
                Map<String, String> params = new HashMap<>();
                params.put("return_attributes", "gender,age");
                params.put("return_landmark", "0");
                //实例化FacePPApi对象
                FacePPApi faceppApi = new FacePPApi(API_KEY, API_SECRET);
                //发起识别请求
                faceppApi.detect(params, BitmapUtil.toByteArray(bitmap), new IFacePPCallBack<DetectResponse>() {
                    @Override
                    public void onSuccess(DetectResponse detectResponse) {
                        Canvas canvas = new Canvas(bitmap);
                        for (Face face : detectResponse.getFaces()) {
                            int height = face.getFace_rectangle().getHeight();
                            int width = face.getFace_rectangle().getWidth();
                            int left = face.getFace_rectangle().getLeft();
                            int top = face.getFace_rectangle().getTop();
                            int right = left + width;
                            int bottom = top + height;
                            Paint paint = new Paint();
                            paint.setColor(YELLOW);
                            paint.setStyle(Paint.Style.STROKE);
                            paint.setStrokeWidth(3);
                            canvas.drawRect(left,top,right,bottom,paint);
                            Paint textPaint = new Paint();
                            textPaint.setStrokeWidth(1);
                            textPaint.setTextSize(30);
                            textPaint.setColor(RED);
                            canvas.drawText(face.getAttributes().getGender().getValue().equals("Female")
                                    ?"女  "+face.getAttributes().getAge().getValue()
                                    :"男  "+face.getAttributes().getAge().getValue()
                                    ,left,top-5,textPaint);
                        }
                        //iv_pic.invalidate();
                        iv_pic.post(new Runnable() {//用另一个线程更新图片比较快
                            @Override
                            public void run() {
                                iv_pic.invalidate();
                            }
                        });
                    }

                    @Override
                    public void onFailed(String s) {
                        Toast.makeText(getApplicationContext(),"请求失败，请稍后再试！",Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        btn_galley.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Toast.makeText(DetectActivity.this,"galley",Toast.LENGTH_SHORT).show();
                //发送调取图片的意图
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, PHOTO_REQUEST_CODE);
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //检测SD卡是否挂载 若挂载返回值为true 所以要在前面加"!"取反
                if(!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)){
                    Toast.makeText(getApplicationContext(),"访问SD卡失败，不能保存图片",Toast.LENGTH_SHORT).show();
                }
                //创建文件夹对象
                File bitmapDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"faceAppPic");
                //如果文件夹不存在则进入语句新建一个
                if(!bitmapDir.exists()){
                    bitmapDir.mkdirs();
                }
                //创建一个新图片文件对象，
                File picFile = new File(bitmapDir,newPicName());
                try {
                    picFile.createNewFile();
                    //把图片写出
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(picFile));
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,bos);
                    //强制把缓冲区的数据写出
                    bos.flush();
                    bos.close();
                    //发送广播提示图库扫描新保存的图片
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(picFile)));
                    Toast.makeText(getApplicationContext(),"保存成功！",Toast.LENGTH_SHORT).show();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                }
            }
        });
    }

    private String newPicName() {
        //格式化日期格式
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmsssss");
        String str =  format.format(new Date())+".jpeg";
        return str;
    }

    private void initView() {
        iv_pic = findViewById(R.id.iv_pic);
        btn_camera = findViewById(R.id.btn_camera);
        btn_detect = findViewById(R.id.btn_detect);
        btn_galley = findViewById(R.id.btn_galley);
        btn_save = findViewById(R.id.btn_save);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //如果请求码为 调取图片则进入语句
        if (requestCode == PHOTO_REQUEST_CODE) {
            //如果调取成功则进入语句
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                //查询uri所指向的路径
                Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                cursor.moveToFirst();//没有这条会报错  指向-1；
                picPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                //获取图片大小
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                //进行图片压缩
                int outWidth = options.outWidth;
                int outHeight = options.outHeight;
                int ivPicWidth = iv_pic.getWidth();
                int ivPicHeight = iv_pic.getHeight();
                int ratioWidth = outWidth / ivPicWidth;
                int ratioHeight = outHeight / ivPicHeight;
                int ratio = Math.max(outHeight, outWidth);//压缩比例
                //根据压缩比例加载图片
                options.inJustDecodeBounds = false;
                options.inSampleSize = ratio;
                options.inMutable = true;
                bitmap = BitmapFactory.decodeFile(picPath, options);
                iv_pic.setImageBitmap(bitmap);
            }
        }

    }
}
